﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Linq;

namespace SDPChecker
{

    public class DependenciesParser
    {
        private XDocument Doc { get; set; }

        public DependenciesParser(TextReader reader)
        {
            Doc = XDocument.Load(reader);
        }

        public IEnumerable<AssemblyInfo> GetDependencies(IEnumerable<string> assemblyNames)
        {
            return from depfor in Doc.Descendants("Dependencies_For")
                   where
                       assemblyNames.Any(
                           name => depfor.Attribute("Assembly") != null && name == GetAssemblyNameForDependencyForElement(depfor))
                   select CreateAssemblyInfoFromDependenciesFor(depfor);
                                   
        }

        private string GetAssemblyNameForDependencyForElement(XElement depfor)
        {
            if (depfor == null) throw new ArgumentNullException("depfor");
            var assemblyAttribute = depfor.Attribute("Assembly");
            if (assemblyAttribute == null)
                throw new ArgumentException("DependencyFor element does not have Assembly attribute", "depfor");

            return assemblyAttribute.Value.Split(' ')[0];
        }

        private AssemblyInfo CreateAssemblyInfoFromDependenciesFor(XElement depfor)
        {
            return new AssemblyInfo(
                GetAssemblyNameForDependencyForElement(depfor),
                from dependency in depfor.Descendants("DependsOn_Name") select new AssemblyInfo(dependency.Value.Split(' ')[0]));
        }
    }
}
